package MainThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;

import org.json.JSONObject;

import Bean.Msg;
import Utils.DateBaseInquiryUtils;
import Utils.DateBaseUpdateUtils;
import Utils.SendMsgUtils;

//负责处理每个线程通信的线程类
public class ServerThread implements Runnable {

	// 定义当前线程所处理的Socket
	private Socket s = null;
	// 该线程所处理的Socket所对应的输入流
	private BufferedReader br = null;
	private String user = null;
	// private PrintStream ps = null;

	public ServerThread(Socket s) throws IOException {
		this.s = s;
		// 初始化该Socket对应的输入流
		br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		// ps = new PrintStream(s.getOutputStream());
	}

	public void run() {
		try {
			String message = null;

			// 采用循环不断从Socket中读取客户端发送过来的数据
			while ((message = readFromClient()) != null) {
				System.out.println(message);

				JSONObject jsinfo = new JSONObject(message);
				int state = jsinfo.getInt("login_reg_chat_ack");

				String from = null;
				String to = null;
				String content = null;

				if (!jsinfo.isNull("from")) {
					from = jsinfo.getString("from");
				}
				if (!jsinfo.isNull("to")) {
					to = jsinfo.getString("to");
				}
				if (!jsinfo.isNull("content")) {
					content = jsinfo.getString("content");
				}

				switch (state) {
				case MyServer.LOGIN:
					String IPFrom = s.getInetAddress().getHostAddress();
					// if (!jsinfo.isNull("from")) {
					// user = jsinfo.getString("from");
					// }
					user = from;
					String[] LnameAndPass = content.split(":");
					String passwordFromDatebase = DateBaseInquiryUtils.getPass(LnameAndPass[0]);
					if (passwordFromDatebase.equals(LnameAndPass[1])) {
						// 登录成功，将IP和姓名加入集合中
						MyServer.mapIP.put(user, IPFrom);

						MyServer.mapSocket.put(user, s);

						// 用Msg的Bean封装，把同意登录消息发送给客户端
						Msg msg = new Msg();
						msg.setLogin_reg_chat_ack(MyServer.LOGIN);
						msg.setContent("SUCCESS");
						msg.setFrom("server");
						msg.setTo(user);
						SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());

					} else {
						Msg msg = new Msg();
						msg.setLogin_reg_chat_ack(MyServer.LOGIN);
						msg.setContent("FAIL");
						msg.setFrom("server");
						msg.setTo(user);
						SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());
					}
					// 通知好友列表
					 String putMsg = DateBaseInquiryUtils.FriendList(user);
					 if(putMsg==null){
						 break;
					 }
					 String[] UAD_friends = putMsg.split(",");
					 for (String friend : UAD_friends) {
						if(MyServer.mapSocket.containsKey(friend)){
							Msg tempMsg = new Msg();
							tempMsg.setLogin_reg_chat_ack(MyServer.UAD);
							tempMsg.setFrom(user);
							tempMsg.setTo(friend);
							tempMsg.setContent("line");
							SendMsgUtils.sendMsg(MyServer.mapSocket.get(friend), new JSONObject(tempMsg).toString());
						}
					}
					break;
				case MyServer.REG:
					String[] RnameAndPass = content.split(":");
					int trueOrFalse = DateBaseInquiryUtils.reg(RnameAndPass[0], RnameAndPass[1]);
					if (trueOrFalse == 1) {
						Msg msg = new Msg();
						msg.setLogin_reg_chat_ack(MyServer.REG);
						msg.setContent("SUCCESS");
						msg.setFrom("server");
						SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());

					} else {
						Msg msg = new Msg();
						msg.setLogin_reg_chat_ack(MyServer.REG);
						msg.setContent("FAIL");
						msg.setFrom("server");
						SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());
					}
					break;
				case MyServer.CHAT:
					// 从map表中，得到收件人的IP地址
//					Socket gs = GetSocketUtil.getSocket(to);
					Socket temp = MyServer.mapSocket.get(to);
//					PrintStream pgs = new PrintStream(gs.getOutputStream());
//					pgs.println(message);
					SendMsgUtils.sendMsg(temp, message);

					break;
				case MyServer.ACK:

					break;

				case MyServer.FRIEND:
					// 先查询好友列表
					String fl = DateBaseInquiryUtils.FriendList(user);
					System.out.println("好友列表" + fl);
					if(fl==null){
						break;
					}
					String[] friends = fl.split(",");
					for (String friend : friends) {
						if (MyServer.mapSocket.containsKey(friend)) {
							Msg msg = new Msg();
							msg.setLogin_reg_chat_ack(MyServer.FRIEND);
							msg.setTo(user);
							msg.setFrom("server");
							msg.setContent("line:" + friend);
							SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());
							msg = null;
						} else {
							Msg msg = new Msg();
							msg.setLogin_reg_chat_ack(MyServer.FRIEND);
							msg.setTo(user);
							msg.setFrom("server");
							msg.setContent("offline:" + friend);
							SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());
							msg = null;
						}
					}
					Msg fmsg = new Msg();
					fmsg.setLogin_reg_chat_ack(MyServer.FRIEND);
					fmsg.setTo(user);
					fmsg.setFrom("server");
					fmsg.setContent("over");
					SendMsgUtils.sendMsg(s, new JSONObject(fmsg).toString());
					fmsg = null;
					
					break;

				case MyServer.ADD:
					if (content.equals("1")) {
						// 先检测是否在线
						if (MyServer.mapIP.containsKey(to)) {
							// 找到在线对方的IP地址,并将添加请求，原封不动的发送给被添加的好友
							Socket Atemp = MyServer.mapSocket.get(to);
							SendMsgUtils.sendMsg(Atemp, message);
						} else {
							Msg msg = new Msg();
							msg.MsgInfo("server", user, MyServer.ADD, "2");
							SendMsgUtils.sendMsg(s, new JSONObject(msg).toString());
						}
					} else if (content.equals("3:A")) {
						// 数据库在这里添加
						System.out.println("数据库在这里添加");
						DateBaseUpdateUtils.addFriends(to, from);
						DateBaseUpdateUtils.addFriends(from, to);

						// 更新好友列表,注意：两个客户端都要添加,更新
						System.out.println("更新好友列表");

						Msg msgg = new Msg();
						msgg.setLogin_reg_chat_ack(MyServer.UAD);
						msgg.setFrom(from);
						msgg.setTo(to);
						msgg.setContent("newfriend");
						Socket Atemp = MyServer.mapSocket.get(to);
						SendMsgUtils.sendMsg(Atemp, new JSONObject(msgg).toString());

						msgg.setLogin_reg_chat_ack(MyServer.UAD);
						msgg.setFrom(to);
						msgg.setTo(from);
						msgg.setContent("newfriend");
						SendMsgUtils.sendMsg(s, new JSONObject(msgg).toString());

					} else if (content.equals("3:R")) {
//						Socket ags = GetSocketUtil.getSocket(to);
						Socket Atemp = MyServer.mapSocket.get(to);
						Msg msg = new Msg();
						msg.MsgInfo(to, from, MyServer.ADD, "3:R");
						SendMsgUtils.sendMsg(Atemp, new JSONObject(msg).toString());
					}
					break;
				case MyServer.EXIT:
					s.close();
					DateBaseUpdateUtils.deleteUserIP(user);
					// MyServer.socketList.remove(s);
					MyServer.mapSocket.remove(user);
					break;

				default:
					break;
				}
			}
		} catch (IOException e) {
		}
	}

	// 定义读取客户端数据的方法
	private String readFromClient() throws IOException {
		try {
			return br.readLine();
		} catch (IOException e) {
		}
		
		 String putMsg = DateBaseInquiryUtils.FriendList(user);
		 if(putMsg!=null){
			 String[] UAD_friends = putMsg.split(",");
			 for (String friend : UAD_friends) {
				 if(MyServer.mapSocket.containsKey(friend)){
					 Msg tempMsg = new Msg();
					 tempMsg.setLogin_reg_chat_ack(MyServer.UAD);
					 tempMsg.setFrom(user);
					 tempMsg.setTo(friend);
					 tempMsg.setContent("offline");
					 SendMsgUtils.sendMsg(MyServer.mapSocket.get(friend), new JSONObject(tempMsg).toString());
				 }
			 }
		 }

		// 删除该Socket。
		String ip = s.getInetAddress().getHostAddress();
		if (user != null) {
			System.out.println("用户:" + user + "---ip:" + ip + "退出聊天室");
		} else {
			System.out.println("ip:" + ip + "登录失败");
		}
		// 从数据库中删除对应的IP地址
		DateBaseUpdateUtils.deleteUserIP(user);
		MyServer.mapSocket.remove(user);
		MyServer.mapIP.remove(user);
		return null;
	}
}
